<template>
  <!-- 自定义对话框 -->
  <custom-dialog ref="customDialogRef" v-slot="{ formData, readonly, mode }" :api-map="orderContractZhengCRUD"
    header="*合同" width="60%" :on-before-set-data="handleDialogSetData" :on-before-save-data="handleDialogSaveData"
    @request-success="handleDialogRequestSuccess" :label-width="120">
    <t-row :gutter="[16, 16]" style="width: 100%">
      <t-col :span="6" >
        <t-form-item label="纯设计" name="isDesigner" :rules="[{ required: true, message: '请选择纯设计' }]">
          <t-radio-group v-model:value="formData.isDesigner">
            <t-radio v-for="_ in dictionaryStore.get('is_type')" :key="_.value" :value="_.value" :readonly="readonly">
              {{ _.label }}
            </t-radio>
          </t-radio-group>
        </t-form-item>
      </t-col>
      <t-col :span="6">
        <t-form-item label="是否有产品" name="isProduct" :rules="[{ required: true, message: '请选择是否有产品' }]">
          <t-radio-group v-model:value="formData.isProduct">
            <t-radio v-for="_ in dictionaryStore.get('is_type')" :key="_.value" :value="_.value" :readonly="readonly">
              {{ _.label }}
            </t-radio>
          </t-radio-group>
        </t-form-item>
      </t-col>
      <t-col :span="12" v-if="mode !== 'create'">
        <t-form-item label="合同编号" name="contractNo" :rules="[{ required: true, message: '请输入合同编号' }]">
          <t-input v-model:value="formData.contractNo" placeholder="请输入合同编号" clearable readonly />
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item label="合同总价" name="contractPrice" :rules="[{ required: true, message: '请输入合同总价' }]">
          <t-input-number v-model:value="formData.contractPrice" :decimal-places="2" min="0"
            :allow-input-over-limit="false" placeholder="请输入合同总价" :readonly="readonly" style="width: 100%" />
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item label="签约时间" name="contractSigningTime" :rules="[{ required: true, message: '请选择签约时间' }]">
          <t-date-picker allow-input v-model:value="formData.contractSigningTime" clearable
            :default-time="dayjs().format('HH:mm:ss')" enable-time-picker placeholder="请选择签约时间" value-type="time-stamp"
            :readonly="readonly" style="width: 100%" />
        </t-form-item>
      </t-col>



      <t-col :span="6" v-if="['0'].includes(formData.isDesigner)">
        <t-form-item label="合同开工时间" v-if="['0'].includes(formData.isDesigner)" name="contractBeginTime" :rules="[
          { required: true, message: '请选择合同开工时间' },
          {
            validator: () => {
              if (!formData.contractEndTime) return true;
              return dayjs(formData.contractBeginTime).isBefore(formData.contractEndTime);
            },
            message: '合同开工时间不能大于合同完工时间',
          },
        ]">
          <t-date-picker allow-input v-model:value="formData.contractBeginTime" clearable placeholder="请选择合同开工时间"
            value-type="time-stamp" :readonly="readonly" style="width: 100%" @change="
              (value) => {
                if (value) {
                  value = dayjs(value).format('YYYY-MM-DD 00:00:00');
                  value = dayjs(value).valueOf();
                }
                formData.contractBeginTime = value ? value : undefined;
              }
            " />
        </t-form-item>
      </t-col>
      <t-col :span="6" v-if="['0'].includes(formData.isDesigner)">
        <t-form-item v-if="['0'].includes(formData.isDesigner)" label="合同完工时间" name="contractEndTime" :rules="[
          { required: true, message: '请选择合同完工时间' },
          {
            validator: () => {
              if (!formData.contractBeginTime) return true;
              return dayjs(formData.contractEndTime).isAfter(formData.contractBeginTime);
            },
            message: '合同完工时间不能小于合同开工时间',
          },
        ]">
          <t-date-picker allow-input v-model:value="formData.contractEndTime" clearable placeholder="请选择合同完工时间"
            value-type="time-stamp" :readonly="readonly" style="width: 100%" @change="
              (value) => {
                if (value) {
                  value = dayjs(value).format('YYYY-MM-DD 23:59:59');
                  value = dayjs(value).valueOf();
                }
                formData.contractEndTime = value ? value : undefined;
              }
            " />
        </t-form-item>
      </t-col>
      <t-col :span="6" v-if="['0'].includes(formData.isDesigner)">
        <t-form-item v-if="['0'].includes(formData.isDesigner)" label="实际开工时间" name="actualBeginTime" :rules="[
          {
            validator: () => {
              if (!formData.actualEndTime) return true;
              return dayjs(formData.actualBeginTime).isBefore(formData.actualEndTime);
            },
            message: '实际开工时间不能大于实际完工时间',
          },
        ]">
          <t-date-picker allow-input v-model:value="formData.actualBeginTime" clearable placeholder="请选择实际开工时间"
            value-type="time-stamp" :readonly="readonly" style="width: 100%" @change="
              (value) => {
                if (value) {
                  value = dayjs(value).format('YYYY-MM-DD 00:00:00');
                  value = dayjs(value).valueOf();
                }
                formData.actualBeginTime = value ? value : undefined;
              }
            " />
        </t-form-item>
      </t-col>
      <t-col :span="6" v-if="['0'].includes(formData.isDesigner)">
        <t-form-item v-if="['0'].includes(formData.isDesigner)" label="实际完工时间" name="actualEndTime" :rules="[
          {
            validator: () => {
              if (!formData.actualBeginTime) return true;
              return dayjs(formData.actualEndTime).isAfter(formData.actualBeginTime);
            },
            message: '实际完工时间不能小于实际开工时间',
          },
        ]">
          <t-date-picker allow-input v-model:value="formData.actualEndTime" clearable placeholder="请选择实际完工时间"
            value-type="time-stamp" :readonly="readonly" style="width: 100%" @change="
              (value) => {
                if (value) {
                  value = dayjs(value).format('YYYY-MM-DD 23:59:59');
                  value = dayjs(value).valueOf();
                }
                formData.actualEndTime = value ? value : undefined;
              }
            " />
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item label="合同文件" name="contractFile">
          <upload v-model:files="formData.contractFile" multiple :readonly="readonly" />
        </t-form-item>
      </t-col>
      <t-col :span="12">

      </t-col>
      <t-col :span="12">
        <t-form-item label="施工模板" name="stageModelId" :rules="[{ required: true, message: '请选择施工模板' }]">
          <t-select v-model:value="formData.stageModelId" placeholder="请选择施工模板" clearable filterable
            :options="stageModelOptions" :keys="{ value: 'id', label: 'name' }" readonly/> 
          <t-button @click="handleOpenEngineeringDialog">
            选择施工模板
          </t-button>
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item label="备注" name="remark">
          <t-textarea v-model:value="formData.remark" placeholder="请输入备注" :readonly="readonly" />
        </t-form-item>
      </t-col>
      <t-col :span="12">
        <t-form-item label="赠品" name="gift">
          <div style="width: 100%">
            <t-table row-key="id" :data="formData.gift" :columns="[
              { colKey: 'id', title: '赠品名称', align: 'center',width: 150 },
              { colKey: 'fileUrl', title: '赠品图片',align: 'center', width: 150 },
              { colKey: 'money', title: '赠品价值金额', align: 'center', width: 150 },
              { colKey: 'operation', title: '操作', align: 'center', width: 70, fixed: 'right' },
            ]" bordered size="small" stripe hover>
              <template #id="{ row, rowIndex }">
                <t-form-item label="赠品名称" :name="`gift[${rowIndex}].id`" :rules="[
                  { required: true, message: '请选择赠品名称' },

                ]" label-width="0">
                  <t-select v-model:value="row.id" clearable filterable placeholder=""
                    @change="handleSelectChange($event, row, formData.gift)">
                    <t-option v-for="_ in giftSelectList" :key="_.id" :value="_.id" :label="_.name">
                      {{ _.name }}
                    </t-option>
                  </t-select>
                </t-form-item>
              </template>
              <template #fileUrl="{ row, rowIndex }">
                <t-form-item label="赠品图片" :name="`gift[${rowIndex}].fileUrl`"
                  :rules="[{ required: true, message: '请选择赠品图片' }]" label-width="0">
                  <image-viewer v-if="row.fileUrl" :images="[row.fileUrl]" width="80px" height="80px" />
                </t-form-item>
              </template>
              <template #operation="{ rowIndex }">
                <t-popconfirm v-if="!readonly" content="确认要删除该项吗？" @confirm="formData.gift.splice(rowIndex, 1)">
                  <t-link theme="danger"> 删除 </t-link>
                </t-popconfirm>
              </template>
            </t-table>
            <t-button v-if="!readonly" block @click="formData.gift.push({})"> 添加赠品 </t-button>
          </div>
        </t-form-item>
      </t-col>
      <t-col :span="12" v-if="['0'].includes(formData.isDesigner)">
        <t-form-item v-if="['0'].includes(formData.isDesigner)" label="分期付款" name="payList"
          :rules="[{ required: true, message: '请选择分期付款' }]">
          <div style="width: 100%">
            <t-table row-key="id" :data="formData.payList" :columns="[
              { colKey: 'payNumber', title: '收款期数',align: 'center', },
              { colKey: 'paymentStage', title: '收款阶段' ,align: 'center',},
              { colKey: 'proportion', title: '收款比例(%)' ,align: 'center',},
              { colKey: 'amountOfMoney',align: 'center', title: '期款金额(元)' },
              { colKey: 'xjje',align: 'center', title: '洽商金额(元)' },
              { colKey: 'reminderForCollectionStage', title: '收款提醒阶段', align: 'center',width: 280 },
              // { colKey: 'operation', title: '操作', width: 70, fixed: 'right' },
            ]" bordered size="small" stripe hover>
              <template #amountOfMoney="{ row, rowIndex }">
                {{ formData.contractPrice ? (row.proportion * formData.contractPrice * 0.01).toFixed(2) : '' }}
              </template>
              <template #xjje="{ row, rowIndex }">
                <a href="">{{ row.xjje }}</a>
              </template>
              <template #reminderForCollectionStage="{ row, rowIndex }">
                <t-cascader v-model:value="row.reminderForCollectionStage" :options="stageTree"
                  :keys="{ value: 'id', label: 'stageName' }" placeholder="" filterable clearable :readonly="true"
                  class="text-only-cascader" />
              </template>
              <template #operation="{ rowIndex }">
                <t-popconfirm v-if="!readonly" content="确认要删除该项吗？" @confirm="formData.payList.splice(rowIndex, 1)">
                  <t-link theme="danger"> 删除 </t-link>
                </t-popconfirm>
              </template>
            </t-table>
            <t-button v-if="!readonly" block @click="handleOpenCollectionDialog"> 添加分期 </t-button>
          </div>
        </t-form-item>
      </t-col>












    </t-row>
  </custom-dialog>
  <collection-dialog ref="collectionDialogRef" @confirm="handleTemplateConfirm" />
  <engineering-dialog  ref="engineeringDialogRef" @confirm="handleEngieeringConfirm" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { ref, useTemplateRef, watch } from 'vue';

import { orderContractZhengCRUD } from '@/api/finance/contract';
import { GiftProjectListCRUD } from '@/api/budget/gift-project';
import { collectionConfigCRUD, engineeringConfigCRUD, engineeringModelCRUD } from '@/api/config/common-config';
import CustomDialog from '@/components/custom/dialog/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import CollectionDialog from './CollectionDialog.vue';
import EngineeringDialog from './EngineeringDialog.vue';
import Upload from '@/components/upload/index.vue';
import listToTree from '@/utils/listToTree';
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// props
const props = defineProps({
  // 公司id
  companyId: {
    type: Number,
  },
});
// 施工模板模板列表
const stageModelOptions = ref([]);
// 处理获取施工模板模板列表
const handleGetstageModelOptions = () => {
  const params = {
    // companyId: props.companyId,
    pageSize: -1,
  };
  engineeringModelCRUD.page(params).then((data) => {
    stageModelOptions.value = data.list;
  });
};
handleGetstageModelOptions();
// 赠品下拉框
const giftSelectList = ref([]);
// 处理获取赠品下拉框列表
const handleGetGiftSelectList = () => {
  const params = {
    pageSize: -1,
  };
  GiftProjectListCRUD.page(params)
    .then((data) => {
      giftSelectList.value = data.list

    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetGiftSelectList();
// 精简节点树
const stageTree = ref([]);
// 处理获取精简节点
const handleGetSimpleStageTree = () => {
  const params = {
    pageSize: -1
  }
  engineeringConfigCRUD.page(params).then((data) => {
    stageTree.value = listToTree(data.list);
  });
};
handleGetSimpleStageTree();
const handleSelectChange = (value: any, row: any, gift: any[]) => {
  // 1. 根据选中的值，从 giftSelectList 中查找对应的数据
  const selectedGift = giftSelectList.value.find(item => item.id === value);
  if (!selectedGift) return;
  // 2. 检查当前选中的赠品是否已经在其他行中被选择过
  const isDuplicate = gift.some(
    (item) => item.name === selectedGift.name && item.id == value
  );

  if (isDuplicate) {
    // 3. 如果赠品已经被选择过，提示用户并阻止赋值
    row.id = ''
    row.fileUrl = ''
    row.money = ''
    row.name = ''
    MessagePlugin.warning('该赠品已被选择，请选择其他赠品');
    return;
  }
  // 4. 如果赠品未被选择过，更新当前行的值
  row.fileUrl = selectedGift.fileUrl
  row.money = selectedGift.money
  row.name = selectedGift.name

  console.log(selectedGift);

}
// emits
const emits = defineEmits(['requestSuccess']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
const handleDialogSetData = (params: Record<string, any>) => {

  if (!params.contractFile) params.contractFile = [];

};
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
  // handleGetPayList(mode);
};

// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {
  if (params.gift.length > 0) {
    params.giftIds = params.gift.map((item: any) => item.id)
    delete params.gift
  } else {
    params.giftIds = []
    delete params.gift
  }
  if (params.isDesigner == '1') {
    params.payList = []
  } else {
    params.payList.forEach((item: any) => {
      item.amountOfMoney = item.proportion * params.contractPrice * 0.01
    })
  }

};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};

// 收款模板对话框ref
const collectionDialogRef = useTemplateRef('collectionDialogRef');

// 处理打开收款模板对话框
const handleOpenCollectionDialog = () => {
  collectionDialogRef.value.open()
  console.log(11);

};
// 处理模板确认选择
const handleTemplateConfirm = (selectedData: any, collectionModelId: any) => {
  const formData = customDialogRef.value.formData;
  formData.payList = []
  formData.collectionModelId = collectionModelId
  // 清空现有数据或保留现有数据（根据需求选择）
  // formData.payList = []; // 如果选择替换现有数据

  // 添加新数据
  selectedData.forEach(item => {
    // 如果合同总价已填写，计算金额
    if (formData.contractPrice) {
      item.amountOfMoney = (item.proportion * formData.contractPrice * 0.01).toFixed(2);
    }

    formData.payList.push({ ...item });
  });
};
// 施工模板
const engineeringDialogRef = useTemplateRef('engineeringDialogRef');
// 处理打开施工模板对话框
const handleOpenEngineeringDialog = () => {
  engineeringDialogRef.value.open()
};
// 处理模板确认选择
const handleEngieeringConfirm = (stageModelId: any) => {
  const formData = customDialogRef.value.formData;
  formData.stageModelId = stageModelId
  
};
defineExpose({
  open: handleOpenDialog,
});
</script>

<style lang="less" scoped>
.text-only-cascader {
  :deep(.t-input__suffix-icon) {
    display: none;
  }

}
</style>
